'use strict'

const wxTpl = require('../../config/wechat/wxTpl')
const wechatApi = require('../api').wechat
const moment = require('moment')

/**
 * 微信公众号 API
 */
const WechatApi = {
  /**
   * 获取 token
   */
  async getToken(appId, appSecret) {
    const data = await wechatApi.GetToken({
      grant_type: 'client_credential',
      appid: appId,
      secret: appSecret,
    })
    return data
  },
  /**
   * 创建临时二维码
   */
  async createTmpQRCode(token, scene_str, time = 2592000) {
    const data = await wechatApi.CreateTmpQRCode(
      {
        access_token: token,
      },
      {
        expire_seconds: time,
        action_name: 'QR_STR_SCENE',
        action_info: {
          scene: {
            scene_str,
          },
        },
      }
    )
    return data
  },
  /**
   * 创建永久二维码
   */
  async createLimitQRCode(token, scene_str) {
    const data = await wechatApi.CreateLimitQRCode(
      {
        access_token: token,
      },
      {
        action_name: 'QR_LIMIT_STR_SCENE',
        action_info: {
          scene: {
            scene_str,
          },
        },
      }
    )
    return data
  },
  /**
   * 发送小程序
   * @param {*} openid
   * @param {*} mina
   */
  async sendMinaMsg(token, openid, mina) {
    const data = await wechatApi.SendMinaMsg(
      {
        access_token: token,
      },
      {
        touser: openid,
        msgtype: 'miniprogrampage',
        miniprogrampage: mina,
      }
    )
    return data
  },
  /**
   * 设置菜单
   * @param {*} menuArray
   */
  async createMenu(token, menuArray) {
    const data = await wechatApi.CreateMenu(
      {
        access_token: token,
      },
      {
        button: menuArray,
      }
    )
    return data
  },

  /**
   * 查询菜单
   */
  async getMenu(token) {
    const data = await wechatApi.GetMenu({
      access_token: token,
    })
    return data
  },

  /**
   * 获取用户基本信息（包括UnionID机制）
   * @param {*} openid
   */
  async getUserInfo(token, openid) {
    const data = await wechatApi.GetUserInfo({
      access_token: token,
      openid,
      lang: 'zh_CN',
    })
    return data
  },

  /**
   * 行驶证识别
   */
  async vehicleLicense(token, image) {
    if (typeof image === 'string') {
      const data = await wechatApi.VehicleLicense(
        {
          access_token: token,
          type: 'photo',
          img_url: image,
        },
        {}
      )
      return data
    }
    const data = await wechatApi.VehicleLicenseUpload(
      {
        access_token: token,
        type: 'photo',
      },
      {
        img: image,
      }
    )
    return data
  },

  /**
   * 小程序的图片智能裁剪能力
   */
  async aiCrop(token, img_url) {
    const data = await wechatApi.AiCrop(
      {
        access_token: token,
        img_url,
      },
      {}
    )
    return data
  },

  // ?type=MODE&img_url=ENCODE_URL&access_token=ACCESS_TOCKEN

  /**
   * 推送模板消息：
   * 1、预约车主：1）预约完成后推送预约成功通知
   *            2）预约到期提醒：提前2小时提醒
   * 2、站长：1）预约提醒：新的客户预约下单
   *         2）入场提醒：预约客户入场提醒
   * 3、前台：1）有新的预约客户
   * 4、中介：1）有新的代驾订单
   * 5、管理员：1）有新订单
   *
   * @param {String} currentToken 当前 token
   * @param {String} tplMark 模板标识
   * @param {String} openId 接收的用户 openid
   * @param {String, Object} location String: H5页面跳转地址 / Object: {appid, pagepath} 小程序appid和路径
   * @param {Array} tplArrData 模板数据
   */
  async sendWechatTplMsg(currentToken, tplMark, openId, location, tplArrData) {
    // 当前取出模板配置信息
    const currentTpl = wxTpl[tplMark]
    if (!currentTpl) {
      throw `暂无该模板，请检查 config/wechat/wxTpl 是否存在 ${tplMark}`
    }
    // 转换模板数据
    const { tpl_id, tpl_title, tpl_value_prefix } = currentTpl
    const tplData = {}
    for (let i = 0; i < tpl_value_prefix.length; i++) {
      if (tplArrData[i]) {
        tplData[tpl_value_prefix[i].key] = {
          value:
            typeof tplArrData[i] === 'string'
              ? tplArrData[i]
              : tplArrData[i].value,
          color:
            typeof tplArrData[i] === 'object'
              ? tplArrData[i].color
                ? tplArrData[i].color
                : tpl_value_prefix[i].color
              : tpl_value_prefix[i].color,
        }
      }
    }
    const reqData = {
      template_id: tpl_id,
      url: typeof location === 'string' ? location : undefined,
      miniprogram:
        typeof location === 'object'
          ? { appid: location.appid, pagepath: location.pagepath }
          : undefined,
      data: tplData,
    }
    const sendApi = async sendApiData => {
      const data = await wechatApi.SendWechatTplMsg(
        {
          access_token: currentToken,
        },
        sendApiData
      )
      return data
    }
    let apiD
    if (typeof openId === 'string') {
      apiD = await sendApi({
        ...reqData,
        touser: openId,
      })
    } else {
      apiD = []
      for (let r = 0; r < openId.length; r++) {
        apiD.push(
          await sendApi({
            ...reqData,
            touser: openId[r],
          })
        )
      }
    }
    return {
      tpl_title,
      apiResult: apiD,
      ...reqData,
    }
  },
  /**
   * 获取用户列表
   */
  async getOpenidList(token, NEXT_OPENID) {
    NEXT_OPENID = NEXT_OPENID ? NEXT_OPENID : ''
    const { data } = await wechatApi.GetOpenidList({
      access_token: token,
      NEXT_OPENID,
    })
    return data
  },
  /**
   * 批量获取用户基本信息
   */
  async batchgetUserInfo(token, arr) {
    arr = await arr.map(item => {
      return {
        openid: item,
        lang: 'zh_CN',
      }
    })
    const { data } = await wechatApi.BatchgetUserInfo(token, {
      user_list: arr,
    })
    return data
  },
  /*
   ** randomWord 产生任意长度随机字母数字组合
   ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
   ** xuanfeng 2014-08-28
   */

  randomWord(randomFlag, min, max) {
    let str = '',
      range = min
    const arr = [
      '0',
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'i',
      'j',
      'k',
      'l',
      'm',
      'n',
      'o',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'I',
      'J',
      'K',
      'L',
      'M',
      'N',
      'O',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z',
    ]

    // 随机产生
    if (randomFlag) {
      range = Math.round(Math.random() * (max - min)) + min
    }
    for (let i = 0; i < range; i++) {
      const pos = Math.round(Math.random() * (arr.length - 1))
      str += arr[pos]
    }
    return str
  },

  /**
   * 新版推送模板消息：
   * @param {String} currentToken 当前 token
   * @param {String} tplMark 模板标识
   * @param {String} openId 接收的用户 openid
   * @param {String} url String: H5页面跳转地址
   * @param {Object} {appid, pagepath} 小程序appid和路径
   * @param {String} wxAppid 公众号appid，要求与小程序有绑定且同主体
   * @param {String} minaAppid 小程序appid
   * @param {Array} tplArrData 模板数据
   */
  async subscribeSend({ currentToken, tplMark, openId, minaPage, tplArrData }) {
    // 当前取出模板配置信息
    const currentTpl = wxTpl[tplMark]
    if (!currentTpl) {
      throw `暂无该模板，请检查 config/wechat/wxTpl 是否存在 ${tplMark}`
    }
    // 转换模板数据
    const { tpl_id, tpl_title, tpl_value_prefix } = currentTpl
    const tplData = {}
    for (let i = 0; i < tpl_value_prefix.length; i++) {
      if (tplArrData[i]) {
        tplData[tpl_value_prefix[i].key] = {
          value:
            typeof tplArrData[i] === 'string'
              ? tplArrData[i]
              : tplArrData[i].value,
          color:
            typeof tplArrData[i] === 'object'
              ? tplArrData[i].color
                ? tplArrData[i].color
                : tpl_value_prefix[i].color
              : tpl_value_prefix[i].color,
        }
      }
    }

    const reqData = {
      page: minaPage,
      lang: 'zh_CN',
      data: tplData,
      template_id: tpl_id,
    }

    const sendApi = async sendApiData => {
      const data = await wechatApi.SubscribeSend(
        {
          access_token: currentToken,
        },
        sendApiData
      )
      return data
    }
    let apiD
    if (typeof openId === 'string') {
      apiD = await sendApi({
        ...reqData,
        touser: openId,
      })
    } else {
      apiD = []
      for (let r = 0; r < openId.length; r++) {
        apiD.push(
          await sendApi({
            ...reqData,
            touser: openId[r],
          })
        )
      }
    }
    return {
      tpl_title,
      apiResult: apiD,
      ...reqData,
    }
  },

  /**
   * 自定义发送
   * @param {*} openid
   * @param {*} mina
   */
  async diySendWxMsg(token, openid, msgtype, wxData) {
    const data = await wechatApi.SendMinaMsg(
      {
        access_token: token,
      },
      {
        touser: openid,
        msgtype,
        ...wxData,
      }
    )
    return data
  },

  // 公众号模板消息
  async publicNotice(token, openid, wxData) {
    const noticeData = {
      first: {
        value: '您有一条新的处罚通知待处理',
        color: '#173177',
      },
      keyword1: {
        value: wxData.punish_type,
        color: '#173177',
      },
      keyword2: {
        value: moment().format('YYYY年MM月DD日HH点mm分ss秒'),
        color: '#173177',
      },
      keyword3: {
        value: '佛山电动车协会',
        color: '#173177',
      },
      remark: {
        value: '企业有骑手违法行为需要处理,点击进入小程序处理...',
        color: '#173177',
      },
    }
    const pagepath = `pages/index?identity=admin&admin_id=${wxData.admin_id}&notice_id=${wxData.notice_id}`
    const data = await this.wxNotice(token, openid, pagepath, noticeData)
    console.log(data, '通知结果')
    return data
  },

  async wxNotice(token, openid, pagepath, noticeData) {
    return await wechatApi.PublicNotice(
      { access_token: token },
      {
        touser: openid,
        template_id: '2K_JsqCNQGDASK-ZWoZbfOeqvS59a0fMGKCdjatF0qM',
        miniprogram: {
          appid: 'wxbe1f44417f9c86f5',
          pagepath,
        },
        data: noticeData,
      }
    )
  },

  // 公众号消息  处罚企业
  async publicPunishCompanyNotice(token, openid, wxData) {
    const noticeData = {
      first: {
        value: '您有一条新的处罚通知待处理',
        color: '#173177',
      },
      keyword1: {
        value: wxData.punish_type,
        color: '#173177',
      },
      keyword2: {
        value: moment().format('YYYY年MM月DD日HH点mm分ss秒'),
        color: '#173177',
      },
      keyword3: {
        value: '佛山电动车协会',
        color: '#173177',
      },
      remark: {
        value: '企业有骑手违法行为需要处理,点击进入小程序处理...',
        color: '#173177',
      },
    }
    const pagepath = `pages/index?identity=admin&admin_id=${wxData.admin_id}&notice_id=${wxData.notice_id}`
    const data = await this.wxNotice(token, openid, pagepath, noticeData)
    console.log(data, '通知结果')
    return data
  },
}
module.exports = WechatApi
